package com.renchunlin.keypadview.view

import android.content.Context
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.StateListDrawable
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.renchunlin.keypadview.R
import com.renchunlin.keypadview.utils.SizeUtils

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/7/8.
 * PS: Not easy to write code, please indicate.
 */
class KeypadView : ViewGroup {

    companion object {
        const val DEFAULT_TEXT_SIZE = 15

        //4行
        const val DEFAULT_ROW = 4

        //3列
        const val DEFAULT_COLUMN = 3

        const val DEFAULT_MARGIN = 2f
    }

    var mTextColor = -1
    var mTextSize = 0f
    var itemPressBgColor = -1
    var itemNormalBgColor = -1
    var itemMargin = -1

    val row = DEFAULT_ROW
    val column = DEFAULT_COLUMN

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        initAttrs(context, attrs)
        setUpItem()
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?) {
        val a = context.obtainStyledAttributes(attrs, R.styleable.KeypadView)
        //获取属性
        mTextColor = a.getColor(
            R.styleable.KeypadView_numberColor,
            ContextCompat.getColor(context, R.color.white)
        )
        mTextSize =
            a.getDimensionPixelSize(R.styleable.KeypadView_numberSize, DEFAULT_TEXT_SIZE).toFloat()
        itemPressBgColor = a.getColor(
            R.styleable.KeypadView_itemPressColor,
            ContextCompat.getColor(context, R.color.key_item_press_color)
        )
        itemNormalBgColor = a.getColor(
            R.styleable.KeypadView_itemNormalColor,
            ContextCompat.getColor(context, R.color.key_item_color)
        )
        itemMargin = a.getDimensionPixelSize(
            R.styleable.KeypadView_itemMargin,
            SizeUtils.dip2px(DEFAULT_MARGIN).toInt()
        )
        a.recycle()
    }

    private fun setUpItem() {
        removeAllViews()
        for (i in 0 until 11) {
            val item = TextView(context)
            //内容
            if (i == 10) {
                item.tag = true
                item.text = "删除"
            } else {
                item.tag = false
                item.text = i.toString()
            }
            //大小
            item.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTextSize)
            //居中
            item.gravity = Gravity.CENTER
            //字体颜色
            item.setTextColor(mTextColor)
            //设置背景
            item.background = providerItemBg()
            item.setOnClickListener {

            }
            addView(item)
            Log.i("chen", "数量: $i")
        }
    }

    private fun providerItemBg(): Drawable {
        //按下去bg
        val pressDrawable = GradientDrawable()
        pressDrawable.setColor(itemPressBgColor)
        pressDrawable.cornerRadius = SizeUtils.dip2px(5f)
        val bg = StateListDrawable()
        bg.addState(intArrayOf(android.R.attr.state_pressed), pressDrawable)
        //普通状态bg
        val normalDrawable = GradientDrawable()
        normalDrawable.setColor(itemNormalBgColor)
        normalDrawable.cornerRadius = SizeUtils.dip2px(5f)
        bg.addState(intArrayOf(0), normalDrawable)
        return bg
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //padding
        val verticalPadding = paddingTop + paddingBottom
        val horizontalPadding = paddingLeft + paddingRight
        //测量孩子
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)
        Log.i("chen", "widthSize: $widthSize")
        Log.i("chen", "heightSize: $heightSize")
        val perItemWidth = (widthSize - (column + 1) * itemMargin - horizontalPadding) / column
        val perItemHeight = (heightSize - (row + 1) * itemMargin - verticalPadding) / row
        val normalWidthSpec = MeasureSpec.makeMeasureSpec(perItemWidth, MeasureSpec.EXACTLY)
        val deleteWidthSpec =
            MeasureSpec.makeMeasureSpec(perItemWidth * 2 + itemMargin, MeasureSpec.EXACTLY)
        val heightSpec = MeasureSpec.makeMeasureSpec(perItemHeight, MeasureSpec.EXACTLY)
        for (i in 0 until childCount) {
            val item = getChildAt(i)
            val isDelete = item.tag as Boolean
            item.measure(if (isDelete) deleteWidthSpec else normalWidthSpec, heightSpec)
        }
        //测量自己
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        val childCount = childCount
        val leftPadding = paddingLeft
        val topPadding = paddingTop
        var left = itemMargin + leftPadding
        var top: Int
        var right: Int
        var bottom: Int
        for (i in 0 until childCount) {
            val rowIndex = i / column
            val columnIndex = i % column
            if (columnIndex == 0) {
                left = itemMargin + leftPadding
            }
            val item = getChildAt(i)
            top = rowIndex * item.measuredHeight + itemMargin * (rowIndex + 1) + topPadding
            right = left + item.measuredWidth
            bottom = top + item.measuredHeight
            item.layout(left, top, right, bottom)
            left += item.measuredWidth + itemMargin
        }
    }
}